<template>
  <div class="wallet box lh-2">
    <div>
      <span>{{ $t('钱包地址') }}：</span>
      <span>{{ fromAddressHide }}</span>
    </div>
    <div>
      <span class="cl-success">{{ $t('USDT') }}：</span>
      <span>{{ balance }}</span>
    </div>
    <div>
      <span class="cl-success">{{ $t('HASH') }}：</span>
      <span>{{ pandax }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import mitt from 'js/mitt'
import { showError, toNumber } from 'js/utils'

const fromAddressHide = ref(window.fromAddressHide)
const balance = ref(0)
const pandax = ref(0)
const coupon = ref(0)

getBalance()
mitt.on('refresh', getBalance)

// 获取钱包余额
async function getBalance() {
  balance.value = await getAccountBalance()
  pandax.value = await getPandaxBalance()
  coupon.value = await getCouponBalance()
}

// 获取账户余额
function getAccountBalance() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取账户余额')
      const balance = await usdtContract.context.methods
        .balanceOf(fromAddress)
        .call()
      const balanceInBigNumber = toNumber(balance)
      console.log(`获取账户余额成功：${balanceInBigNumber}`)
      resolve(balanceInBigNumber)
    } catch (err) {
      showError('获取账户余额失败')
      console.error('获取账户余额失败')
      console.error(err)
    }
  })
}

// 获取Pandax余额
function getPandaxBalance() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取Pandax余额')
      const balance = await pandaxContract.context.methods
        .balanceOf(fromAddress)
        .call()
      const balanceInBigNumber = toNumber(balance)
      console.log(`获取Pandax余额成功：${balanceInBigNumber}`)
      resolve(balanceInBigNumber)
    } catch (err) {
      showError('获取Pandax余额失败')
      console.error('获取Pandax余额失败')
      console.error(err)
    }
  })
}

// 获取Coupon余额
function getCouponBalance() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取Coupon余额')
      const balance = await couponContract.context.methods
        .balanceOf(fromAddress)
        .call()
      const balanceInBigNumber = toNumber(balance)
      console.log(`获取Coupon余额成功：${balanceInBigNumber}`)
      resolve(balanceInBigNumber)
    } catch (err) {
      showError('获取Coupon余额失败')
      console.error('获取Coupon余额失败')
      console.error(err)
    }
  })
}
</script>

<style lang="scss" scoped></style>
